package com.menhai.personmanagement.services;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.menhai.personmanagement.entity.*;
import com.menhai.personmanagement.entity.co.MbPopulationCo;
import com.menhai.personmanagement.entity.vo.FrontPageVo;
import com.menhai.personmanagement.entity.vo.MbPopulationTemplete;
import com.menhai.personmanagement.entity.vo.MbPopulationVo;
import com.menhai.personmanagement.entity.vo.SaveArchivesVo;
import com.menhai.personmanagement.mapper.*;
import com.menhai.personmanagement.utils.CalculationTool;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.Collator;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.menhai.personmanagement.utils.ExcelOperUtil.addSelect;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author shikun
 * @since 2021-12-02
 */
 @Service
public class IMbPopulationService{

   @Autowired
   private MbPopulationMapper mbPopulationMapper;

   @Autowired
   private SysUserMapper sysUserMapper;

   @Autowired
   private ReportCardMapper reportCardMapper;

   @Autowired
   private CodelistMapper codelistMapper;

   @Autowired
   private MbTreatmentInformationMapper treatmentInformationMapper;

   @Autowired
   private ReportHealthrecordMapper reportHealthrecordMapper;

   @Autowired
   private HealthCheckMapper healthCheckMapper;

   @Autowired
   private ICodelistService codelistService;

   /**
    * @describe 心电图 根据 村民id 查询 村民
    * @param mbPopulation
    * @Return com.menhai.personmanagement.entity.MbPopulation
    * @Date 2022/5/16 9:20
    * @author shikun
    */
    public MbPopulation selectEcgBypopulationId(MbPopulation mbPopulation){
        return CalculationTool.getAgeAndSexobject(mbPopulationMapper.selectById(mbPopulation.getId()));
    }

   public List findHouseNumber(String houseNumber, String level, String userid){
       QueryWrapper wrapper = new QueryWrapper();
       wrapper.like("houseNumber", houseNumber);
       wrapper.likeRight("superiorCode", level);
       wrapper.eq("isAvailable", 1);
       return mbPopulationMapper.selectList(wrapper);
   }


   /**
    * @describe 下级村民
    * @param superiorCode
    * @Return java.util.List<com.menhai.personmanagement.entity.MbPopulation>
    * @Date 2022/2/25 13:23
    * @author shikun
    */
    public List<MbPopulation> selectresidentlist(String superiorCode){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.likeRight("superiorCode", superiorCode);
        wrapper.eq("isAvailable", 1);
        return mbPopulationMapper.selectList(wrapper);
    }

    /**
     * @describe id查询村民
     * @param id
     * @Return com.menhai.personmanagement.entity.MbPopulation
     * @Date 2022/2/25 13:23
     * @author shikun
     */
    public MbPopulation searchByStringId(String id){
        return CalculationTool.getAgeAndSexobject(mbPopulationMapper.selectById(id));
    }

   /**
    * @describe 残疾人员统计表
    * @param mbPopulationCo
    * @Return com.baomidou.mybatisplus.core.metadata.IPage<com.menhai.personmanagement.entity.MbPopulation>
    * @Date 2022/2/21 10:47
    * @author shikun
    */
    public IPage<MbPopulation> selectBydisabled(MbPopulationCo mbPopulationCo) {
        Page<MbPopulation> page = new Page<>(mbPopulationCo.getPageIndex(), mbPopulationCo.getPageSize());
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("health", "残疾");
        if(mbPopulationCo.getCreatedate()!=null){
            queryWrapper.likeRight("createdate", mbPopulationCo.getCreatedate());
        }
        queryWrapper.orderByAsc("superiorCode");
        queryWrapper.likeRight("superiorCode", mbPopulationCo.getSuperiorCode());
        queryWrapper.eq("isAvailable", 1);
        return setVillageName(mbPopulationMapper.selectPage(page,queryWrapper));
    }

    public List gecunrenshu(String state,String local){
        return mbPopulationMapper.gecunrenshu(state,local);
    }

    public List gecunren(){
        return mbPopulationMapper.gecunren();
    }

    public List xianshicun(String hosnum){
        return mbPopulationMapper.xianshicun(hosnum);
    }

    public List usergecunrenshu(){
        return mbPopulationMapper.usergecunrenshu();
    }
    public List codelistallin(){
        return mbPopulationMapper.codelistallin();
    }

    public List codelistBycodelistId(String hosnum){
        return mbPopulationMapper.codelistBycodelistId(hosnum);
    }

    public List codeListBykindCode(){
        return mbPopulationMapper.codeListBykindCode();
    }

    public List healthPlangecunrenshu(){
        return mbPopulationMapper.healthPlangecunrenshu();
    }
    public List usergecunrenshuAndisAvailable(){
        return mbPopulationMapper.usergecunrenshuAndisAvailable();
    }

    public List reportcardtree(){
        return mbPopulationMapper.reportcardtree();
    }

    /**
     * @describe 残疾人员导出
     * @param mbPopulationCo
     * @Return java.util.List<com.menhai.personmanagement.entity.MbPopulation>
     * @Date 2022/2/21 11:51
     * @author shikun
     */
    public List<MbPopulation> exportBydisabled(MbPopulationCo mbPopulationCo) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("health", "残疾");
        if(mbPopulationCo.getCreatedate()!=null){
            queryWrapper.likeRight("createdate", mbPopulationCo.getCreatedate());
        }
        queryWrapper.orderByAsc("superiorCode");
        queryWrapper.likeRight("superiorCode", mbPopulationCo.getSuperiorCode());
        queryWrapper.eq("isAvailable", 1);
        return setVillageName(mbPopulationMapper.selectList(queryWrapper));
    }

    /**
     * @describe 两劳人员
     * @param mbPopulationCo
     * @Return com.baomidou.mybatisplus.core.metadata.IPage<com.menhai.personmanagement.entity.MbPopulation>
     * @Date 2022/2/21 13:55
     * @author shikun
     */
    public IPage<MbPopulation> selectBylianglao(MbPopulationCo mbPopulationCo) {
        Page<MbPopulation> page = new Page<>(mbPopulationCo.getPageIndex(), mbPopulationCo.getPageSize());
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if(mbPopulationCo.getLianglao()!=null && !mbPopulationCo.getLianglao().equals("")){
            queryWrapper.like("lianglao", mbPopulationCo.getLianglao());
        }
        if(mbPopulationCo.getCreatedate()!=null && !mbPopulationCo.getCreatedate().equals("")){
            queryWrapper.likeRight("createdate", mbPopulationCo.getCreatedate());
        }
        queryWrapper.orderByAsc("superiorCode");
        queryWrapper.likeRight("superiorCode", mbPopulationCo.getSuperiorCode());
        queryWrapper.ne("lianglao","");
        queryWrapper.eq("isAvailable", 1);
        return CalculationTool.getAgeAndSex(setVillageName(mbPopulationMapper.selectPage(page,queryWrapper)));
    }

    /**
     * @describe 两劳人员导出
     * @param mbPopulationCo
     * @Return java.util.List<com.menhai.personmanagement.entity.MbPopulation>
     * @Date 2022/2/21 14:17
     * @author shikun
     */
    public List<MbPopulation> exportBylianglao(MbPopulationCo mbPopulationCo) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if(mbPopulationCo.getLianglao()!=null && !mbPopulationCo.getLianglao().equals("")){
            queryWrapper.like("lianglao", mbPopulationCo.getLianglao());
        }
        if(mbPopulationCo.getCreatedate()!=null && !mbPopulationCo.getCreatedate().equals("")){
            queryWrapper.likeRight("createdate", mbPopulationCo.getCreatedate());
        }
        queryWrapper.orderByAsc("superiorCode");
        queryWrapper.likeRight("superiorCode", mbPopulationCo.getSuperiorCode());
        queryWrapper.ne("lianglao","");
        queryWrapper.eq("isAvailable", 1);
        return CalculationTool.getAgeAndSex(setVillageName(mbPopulationMapper.selectList(queryWrapper)));
    }


    /**
     * @describe 军烈属信息
     * @param mbPopulationCo
     * @Return com.baomidou.mybatisplus.core.metadata.IPage<com.menhai.personmanagement.entity.MbPopulation>
     * @Date 2022/2/21 15:02
     * @author shikun
     */
    public IPage<MbPopulation> selectByjunlieshu(MbPopulationCo mbPopulationCo) {
        Page<MbPopulation> page = new Page<>(mbPopulationCo.getPageIndex(), mbPopulationCo.getPageSize());
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if(mbPopulationCo.getJunlieshu()!=null){
            queryWrapper.like("junlieshu", mbPopulationCo.getJunlieshu());
        }
        if(mbPopulationCo.getCreatedate()!=null){
            queryWrapper.likeRight("createdate", mbPopulationCo.getCreatedate());
        }
        queryWrapper.orderByDesc("createdate");
        queryWrapper.likeRight("superiorCode", mbPopulationCo.getSuperiorCode());
        queryWrapper.ne("junlieshu","");
        queryWrapper.eq("isAvailable", 1);
        return setVillageName(mbPopulationMapper.selectPage(page,queryWrapper));
    }

    /**
     * @describe 军烈属信息导出
     * @param mbPopulationCo
     * @Return java.util.List<com.menhai.personmanagement.entity.MbPopulation>
     * @Date 2022/2/21 15:55
     * @author shikun
     */
    public List<MbPopulation> exportByjunlieshu(MbPopulationCo mbPopulationCo) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if(mbPopulationCo.getJunlieshu()!=null){
            queryWrapper.like("junlieshu", mbPopulationCo.getJunlieshu());
        }
        if(mbPopulationCo.getCreatedate()!=null){
            queryWrapper.likeRight("createdate", mbPopulationCo.getCreatedate());
        }
        queryWrapper.orderByDesc("createdate");
        queryWrapper.likeRight("superiorCode", mbPopulationCo.getSuperiorCode());
        queryWrapper.ne("junlieshu","");
        queryWrapper.eq("isAvailable", 1);
        return setVillageName(mbPopulationMapper.selectList(queryWrapper));
    }

    /**
     * @describe 医保人员信息
     * @param mbPopulationCo
     * @Return com.baomidou.mybatisplus.core.metadata.IPage<com.menhai.personmanagement.entity.MbPopulation>
     * @Date 2022/2/21 15:56
     * @author shikun
     */
    public IPage<MbPopulation> selectBymedicalInsurance(MbPopulationCo mbPopulationCo) {
        Page<MbPopulation> page = new Page<>(mbPopulationCo.getPageIndex(), mbPopulationCo.getPageSize());
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if(mbPopulationCo.getCreatedate()!=null){
            queryWrapper.likeRight("createdate", mbPopulationCo.getCreatedate());
        }
        queryWrapper.orderByDesc("createdate");
        queryWrapper.likeRight("superiorCode", mbPopulationCo.getSuperiorCode());
        queryWrapper.ne("medicalInsurance","");
        queryWrapper.eq("isAvailable", 1);
        return setVillageName(mbPopulationMapper.selectPage(page,queryWrapper));
    }


    public List<MbPopulation> exportBymedicalInsurance(MbPopulationCo mbPopulationCo) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if(mbPopulationCo.getCreatedate()!=null){
            queryWrapper.likeRight("createdate", mbPopulationCo.getCreatedate());
        }
        queryWrapper.orderByDesc("createdate");
        queryWrapper.likeRight("superiorCode", mbPopulationCo.getSuperiorCode());
        queryWrapper.ne("medicalInsurance","");
        queryWrapper.eq("isAvailable", 1);
        return setVillageName(mbPopulationMapper.selectList(queryWrapper));
    }

    public MbPopulation searchByuserId(Long id ,String idnumber){
        QueryWrapper queryWrapper= new QueryWrapper<>();
        if (idnumber!=null&&!idnumber.isEmpty()) {
            queryWrapper.eq("idnumber",idnumber);
            return  mbPopulationMapper.selectOne(queryWrapper);
        }
        return mbPopulationMapper.selectById(id);
    }

    public int addPopluation(MbPopulationVo mbPopulationVo){
        String uuid = UUID.randomUUID().toString();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("idnumber", mbPopulationVo.getIdnumber());
        int count = mbPopulationMapper.selectCount(queryWrapper);
        if(count <= 0) {
            mbPopulationVo.setFamilycode(uuid);
            mbPopulationVo.setIsAvailable(1);
            mbPopulationMapper.insert(mbPopulationVo);
            if (mbPopulationVo.getChildren().size() > 0) {
                for (int i = 0; i < mbPopulationVo.getChildren().size(); i++) {
                    MbPopulation mbPopulation = mbPopulationVo.getChildren().get(i);
//                    temp.setFamilycode(uuid);
//                    temp.setFamilyNumber(mbPopulationVo.getFamilyNumber());
//                    mbPopulationMapper.updateById(temp);
                    if(null != mbPopulation.getFamilyrole() && !mbPopulation.getFamilyrole().equals("")) {//有角色，该家庭成员
                        mbPopulation.setFamilycode(uuid);
                        mbPopulation.setFamilyNumber(mbPopulationVo.getFamilyNumber());
                        mbPopulation.setHouseholder("否");
                        mbPopulationMapper.updateById(mbPopulation);
                    }else{//不是家庭成员
                        mbPopulation.setFamilycode(null);
                        mbPopulation.setFamilyNumber(null);
                        mbPopulation.setHouseholder(null);
                        mbPopulation.setFamilyrole(null);
                        mbPopulationMapper.updateById(mbPopulation);
                    }
                }
            }
            return 1;
        }else{
            return -1;
        }
    }

    public int updateAvailableVal(int id,int isAvailableVal){
        MbPopulation mbPopulation = new MbPopulation();
        mbPopulation.setId(id);
        if (isAvailableVal == 1){
            mbPopulation.setIsAvailable(0);
            return mbPopulationMapper.updateById(mbPopulation);
        }else if (isAvailableVal == 0){
            mbPopulation.setIsAvailable(1);
            return mbPopulationMapper.updateById(mbPopulation);
        }else{
            return -1;
        }
    }

    public int isAvailable(MbPopulation mbPopulation){
        return mbPopulationMapper.updateById(mbPopulation);
    }

    public Page<MbPopulation> getPopulation(int pagesize,int size,String levelnum){
        Page<MbPopulation> page = new Page<>(pagesize,size);
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if(levelnum.length() == 8){
            queryWrapper.eq("superiorCode", levelnum);
        }else {
            queryWrapper.likeRight("superiorCode", levelnum);
        }
        queryWrapper.eq("isAvailable", 1);
        queryWrapper.orderByAsc("houseNumber");
        queryWrapper.orderByDesc("createtime");
        Page<MbPopulation> list1 = mbPopulationMapper.selectPage(page,queryWrapper);
        for (int i=0;i<list1.getRecords().size();i++){
            MbPopulation temp = list1.getRecords().get(i);
            if (temp.getIdnumber()!=null&&!temp.getIdnumber().equals("")){
                temp.setAge(CalculationTool.getAgeAndSex(temp.getIdnumber()).get("age").toString());
            }

            list1.getRecords().set(i,temp);
        }
        return list1;
    }

    public int deletePopulation(int id){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("populationid", id);
        int count = reportCardMapper.selectCount(queryWrapper);
        if (count > 0) {
            return -1;
        }else{
            return mbPopulationMapper.deleteById(id);
        }
    }

    public List searchByUserName(String userId,String level,String name,String menpai){
        QueryWrapper wrapper = new QueryWrapper();
        if(notnull(level)){
            wrapper.likeRight("superiorCode", level);
        }
        if(notnull(name)){
            wrapper.like("name", name);
        }
        if(notnull(menpai)){
            wrapper.eq("houseNumber", menpai);
        }
        wrapper.orderByAsc("createtime");
        List<MbPopulation> list = mbPopulationMapper.selectList(wrapper);
        List l = new ArrayList();
        list.forEach((val)->{
            MbPopulation mp = val;
            if (mp.getIdnumber()!=null&&!mp.getIdnumber().equals("")){
                mp.setAge(CalculationTool.getAgeAndSex(mp.getIdnumber()).get("age").toString());
            }
            l.add(mp);
        });
        return l;
    }

    public int updataPopulation(MbPopulationVo mbPopulationVo){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("idnumber", mbPopulationVo.getIdnumber());
        queryWrapper.ne("id", mbPopulationVo.getId());
        int count = mbPopulationMapper.selectCount(queryWrapper);
        if(count > 0){
            return -1;
        }
        try {


            String familyCode = UUID.randomUUID().toString();
            mbPopulationVo.setFamilycode(familyCode);
            mbPopulationMapper.updateById(mbPopulationVo);
            for (int i = 0; i < mbPopulationVo.getChildren().size(); i++) {
                MbPopulation mbPopulation = mbPopulationVo.getChildren().get(i);
                if(null != mbPopulation.getFamilyrole() && !mbPopulation.getFamilyrole().equals("")) {//有角色，该家庭成员
                    mbPopulation.setFamilycode(familyCode);
                    mbPopulation.setFamilyNumber(mbPopulationVo.getFamilyNumber());
                    mbPopulation.setHouseholder("否");
                    mbPopulationMapper.updateById(mbPopulation);
                }else{//不是家庭成员
                    mbPopulation.setFamilycode(null);
                    mbPopulation.setFamilyNumber(null);
                    mbPopulation.setHouseholder(null);
                    mbPopulation.setFamilyrole(null);
                    mbPopulationMapper.updateById(mbPopulation);
                }
            }
            return 1;
        }catch(Exception e){
            e.printStackTrace();
            return -1;
        }
    }

    public List findFamilyData(String familyCode, int id){
        QueryWrapper queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("familycode", familyCode);
        queryWrapper.ne("id", id);
        queryWrapper.eq("isAvailable", 1);
        queryWrapper.orderByAsc("superiorCode");
        return mbPopulationMapper.selectList(queryWrapper);
    }

    public List findFamily(String huhao){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("familyNumber", huhao);
        wrapper.eq("isAvailable", 1);
        wrapper.orderByAsc("superiorCode");
        return setVillageName(mbPopulationMapper.selectList(wrapper));
    }

    public Page addressList(int pagesize, int pagenum, String level,String name){
       Page page = new Page(pagenum,pagesize);
       QueryWrapper wrapper = new QueryWrapper();
       if(null != name && !name.equals("")){
           wrapper.like("name", name);
       }
       wrapper.likeRight("superiorCode", level);
       wrapper.eq("isAvailable", 1);
       wrapper.orderByAsc("superiorCode");
       return setVillageName(mbPopulationMapper.selectPage(page, wrapper));
    }

    public Page setVillageName(Page<MbPopulation> page){
        List<Codelist> list = codelistMapper.selectByCodeKindCode("YYMC");
        page.getRecords().stream().sorted(Comparator.comparing(MbPopulation::getSuperiorCode)).forEach(v -> {
            Map map = list.stream().filter(c -> c.getCodeValue().equals(v.getSuperiorCode())).collect(Collectors.toMap(k -> k.getCodeValue(),vl -> vl.getCodeName()));
            v.setSuperiorCode(map.get(v.getSuperiorCode()).toString());
        });
        return page;
    }
    public List<MbPopulation> setVillageName(List<MbPopulation> page){
        List<Codelist> list = codelistMapper.selectByCodeKindCode("YYMC");
        page.stream().sorted(Comparator.comparing(MbPopulation::getSuperiorCode)).forEach(v -> {
            Map map = list.stream().filter(c -> c.getCodeValue().equals(v.getSuperiorCode())).collect(Collectors.toMap(k -> k.getCodeValue(),vl -> vl.getCodeName()));
            v.setSuperiorCode(map.get(v.getSuperiorCode()).toString());
        });
        return page.stream().sorted(Comparator.comparing(MbPopulation::getSuperiorCode)).collect(Collectors.toList());
    }

    public Page lowIncome(String level,int pagesize, int pagenum,String name){
        Page page = new Page(pagenum, pagesize);
        QueryWrapper wrapper = new QueryWrapper();
        if(notnull(name)){
            wrapper.like("name", name);
        }
        wrapper.likeRight("superiorCode", level);
        wrapper.eq("lowIncome", "是");
        wrapper.eq("isAvailable", 1);
        wrapper.orderByAsc("superiorCode");
        return setVillageName(mbPopulationMapper.selectPage(page, wrapper));
    }

    public Page unemployment(String level, int pagesize, int pagenum,String name){
        Page page = new Page(pagenum, pagesize);
        QueryWrapper wrapper = new QueryWrapper();
        if(notnull(name)){
            wrapper.like("name", name);
        }
        wrapper.likeRight("superiorCode", level);
        wrapper.eq("isJob","未就业（1学生 2丧失劳动力 3离退休 4料理家务 5无业/毕业无工作 6失业/下岗离岗 7土地被征用其他）");
        wrapper.eq("isAvailable", 1);
        wrapper.orderByAsc("superiorCode");
        return CalculationTool.getAgeAndSex(setVillageName(mbPopulationMapper.selectPage(page, wrapper)));
    }

    public List exprotYoufu(String level,String date){
        List<Codelist> codeList = codelistMapper.getHospitalThree(level);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.likeRight("superiorCode", level);
        List<MbPopulation> list = mbPopulationMapper.selectList(wrapper);
        return dataFormat(list,codeList);
    }

    public List exprotCensus(String level,String minzu,String xueli,String hunyin,String yibao,String jiankang){
        QueryWrapper wrapper = new QueryWrapper();
        if(null != minzu && !minzu.equals("") && !minzu.equals("undefined")){
            wrapper.eq("nation",minzu);
        }
        if(null != xueli && !xueli.equals("") && !xueli.equals("undefined")){
            wrapper.eq("education",xueli);
        }
        if(null != hunyin && !hunyin.equals("") && !hunyin.equals("undefined")){
            wrapper.eq("marriage",hunyin);
        }
        if(null != yibao && !yibao.equals("") && !yibao.equals("undefined")){
            wrapper.eq("medicalInsurance",yibao);
        }
        if(null != jiankang && !jiankang.equals("") && !jiankang.equals("undefined")){
            wrapper.eq("health",jiankang);
        }
        wrapper.likeRight("superiorCode", level);
        wrapper.orderByAsc("superiorCode");
        return CalculationTool.getAgeAndSex(mbPopulationMapper.selectList(wrapper));
    }

    public Page persontotal(String level, int pagesize, int pagenum,String minzu,String xueli,String hunyin,String yibao,String jiankang){
        Page page = new Page(pagenum, pagesize);
        QueryWrapper wrapper = new QueryWrapper();
        if(null != minzu && !minzu.equals("")){
            wrapper.eq("nation",minzu);
        }
        if(null != xueli && !xueli.equals("")){
            wrapper.eq("education",xueli);
        }
        if(null != hunyin && !hunyin.equals("")){
            wrapper.eq("marriage",hunyin);
        }
        if(null != yibao && !yibao.equals("")){
            wrapper.eq("medicalInsurance",yibao);
        }
        if(null != jiankang && !jiankang.equals("")){
            wrapper.eq("health",jiankang);
        }
        wrapper.likeRight("superiorCode", level);
        wrapper.orderByAsc("superiorCode");
        return CalculationTool.getAgeAndSex(mbPopulationMapper.selectPage(page, wrapper));
    }

    public List dataFormat(List<MbPopulation> ge,List<Codelist> cun){
        String[] kw = {"三属","在乡老复员军人","带病回乡退伍军人","两参人员","伤残军人","60周岁农村籍退役士兵"};
        List<Map> list = new LinkedList<>();
        ge.stream().collect(Collectors.groupingBy(MbPopulation::getSuperiorCode)).entrySet().stream().forEach(val -> {
            Map map = new HashMap();
            Arrays.stream(kw).forEach(t -> {
                map.put(t, val.getValue().stream().filter(v -> null != v.getYoufu()? v.getYoufu().contains(t): false).count());
            });
            List<Codelist> cList = new ArrayList<>(cun.stream().filter(cu -> cu.getCodeValue().equals(val.getKey())).collect(Collectors.toList()));
            map.put("cun", cList.get(0).getCodeName());
            list.add(map);
        });

        for(int i=0;i<cun.size();i++){
            boolean temp = true;
            for(int j=0;j<list.size();j++){
                if(cun.get(i).getCodeName().equals(list.get(j).get("cun"))){
                    temp = false;
                }
            }
            if(temp){
                Map map = new HashMap();
                Arrays.stream(kw).forEach(v -> {
                    map.put(v, 0);
                });
                map.put("cun", cun.get(i).getCodeName());
                list.add(map);
            }
        }

        Collections.sort(list, new Comparator<Map>() {
            @Override
            public int compare(Map o1, Map o2) {
                Collator collator=Collator.getInstance(Locale.CHINA);
                return collator.compare(o1.get("cun"),o2.get("cun"));
            }
        });

        return list;
    }

    public List<MbPopulation> exprotAddressList(String level,String name){
       QueryWrapper wrapper = new QueryWrapper();
        if(null != name && !name.equals("")){
            wrapper.like("name", name);
        }
       wrapper.likeRight("superiorCode", level);
       return setVillageName(mbPopulationMapper.selectList(wrapper));
    }

    public List<MbPopulation> exprotLowIncome(String level,String name){
        QueryWrapper wrapper = new QueryWrapper();
        if(notnull(name)){
            wrapper.like("name", name);
        }
        wrapper.likeRight("superiorCode", level);
        wrapper.eq("lowIncome", "是");
        return setVillageName(mbPopulationMapper.selectList(wrapper));
    }

    public List<MbPopulation> exprotUnemployment(String level,String name){
        QueryWrapper wrapper = new QueryWrapper();
        if(notnull(name)){
            wrapper.like("name", name);
        }
        wrapper.likeRight("superiorCode", level);
        wrapper.eq("isJob","未就业（1学生 2丧失劳动力 3离退休 4料理家务 5无业/毕业无工作 6失业/下岗离岗 7土地被征用其他）");
        return CalculationTool.getAgeAndSex(setVillageName(mbPopulationMapper.selectList(wrapper)));
    }

    public Page<MbPopulation> searchPopulation(String name,String sex,String age1,String age2,String idnumber,String tell,String state,int pagesize,int size,String levelnum,String chronic,String zhen,String cun,String houseNumber,String hosnumarray,String local,String familSearch,String id){
        Page<MbPopulation> page = new Page<>(pagesize,size);
        QueryWrapper<MbPopulation> wrapper=new QueryWrapper<>();
        if(null != name && !name.equals(""))
            wrapper.like("name",name);
        if(null != sex && !sex.equals(""))
            wrapper.eq("sex",sex);
        if(null != age1 && !age1.equals(""))
            wrapper.ge("age",age1);
        if(null != age2 && !age2.equals(""))
            wrapper.le("age",age2);
        if(null != idnumber && !idnumber.equals(""))
            wrapper.eq("idnumber",idnumber);
        if(null != tell && !tell.equals(""))
            wrapper.eq("telephony", tell);
        if(null != state && !state.equals(""))
            wrapper.eq("state",state);
        if(null != chronic && !chronic.equals(""))
            wrapper.like("chronic", chronic);

        if(null != houseNumber && !houseNumber.equals("")){
            wrapper.eq("houseNumber", houseNumber);
        }
        if(null != local && !local.equals("")) {
            wrapper.eq("local", local);
        }
        if(null != id && !id.equals("")){
            wrapper.ne("id",id);
        }
        wrapper.eq("isAvailable", 1);
        wrapper.orderByAsc("houseNumber");
        wrapper.orderByDesc("createtime");
        if (null != hosnumarray && !hosnumarray.equals("")){
            wrapper.in("superiorCode", Arrays.stream(hosnumarray.split(",")).collect(Collectors.toList()));
        }else{
            if(null != cun && !cun.equals("")){
                wrapper.eq("superiorCode",cun);
            }else if(null != zhen && !zhen.equals("")){
                wrapper.likeRight("superiorCode",zhen);
            }else {
                wrapper.likeRight("superiorCode", levelnum);
            }
        }
        if (null != familSearch) {
            System.out.println(familSearch);
            if (familSearch.equals("1")) {
//                wrapper.eq("familycode", null);
                wrapper.isNull("familyNumber");
            }
        }
        Page<MbPopulation> p = mbPopulationMapper.selectPage(page,wrapper);
        for(int i=0;i< p.getRecords().size();i++){
            if (p.getRecords().get(i).getIdnumber()!=null&&!p.getRecords().get(i).getIdnumber().equals("")){
                p.getRecords().get(i).setAge(CalculationTool.getAgeAndSex(p.getRecords().get(i).getIdnumber()).get("age").toString());
            }
        }
        return p;
    }
    
    /**
     * 慢病新建报卡  查询人口姓名集合
     * @param patientName
     * @return
     */
    public List<Map<String,Object>> selectReportCardName(String patientName,String hosnum,String mblx){
    	return mbPopulationMapper.selectReportCardName(patientName,hosnum,mblx);
    }
    
    /**
     * 慢病新建报卡  根据id查询人口信息
     * @param id
     * @return
     */
    public Map<String,Object> selectReportCardById(String id,String mblx){
    	//查询该人是否新建过同一慢病类型的报卡
    	int selectIsSame = reportCardMapper.selectIsSame(id, mblx);
    	if(selectIsSame>0){
    		return null;
    	}else{
    		return mbPopulationMapper.selectReportCardById(id);
    	}   	
    }



    /**
     * @describe 查询村民信息
     * @param mbPopulationCo
     * @Return com.baomidou.mybatisplus.core.metadata.IPage<com.menhai.personmanagement.entity.MbPopulation>
     * @Date 2021/12/13 15:41
     * @author shikun
     */
    public IPage<MbPopulation> selectByList(MbPopulationCo mbPopulationCo){
        Page<MbPopulation> page = new Page<>(mbPopulationCo.getPageIndex(),mbPopulationCo.getPageSize());
        QueryWrapper<MbPopulation> wrapper=new QueryWrapper<>();
        if(null != mbPopulationCo.getName() && !mbPopulationCo.getName().equals("")){
            wrapper.like("name",mbPopulationCo.getName());
        }
        if(null != mbPopulationCo.getSex() && !mbPopulationCo.getSex().equals("")){
            wrapper.eq("sex",mbPopulationCo.getSex());
        }
        if(null != mbPopulationCo.getTelephony() && !mbPopulationCo.getTelephony().equals("")){
            wrapper.eq("telephony",mbPopulationCo.getTelephony());
        }
        if(null != mbPopulationCo.getAge1() && !mbPopulationCo.getAge1().equals("")){
            wrapper.ge(true,"age",mbPopulationCo.getAge1());
        }
        if(null != mbPopulationCo.getAge2() && !mbPopulationCo.getAge2().equals("")){
            wrapper.le(true,"age",mbPopulationCo.getAge2());
        }
        if(null !=  mbPopulationCo.getIdnumber() && ! mbPopulationCo.getIdnumber().equals("")){
            wrapper.eq("idnumber",mbPopulationCo.getIdnumber());
        }
        if(null != mbPopulationCo.getSuperiorCode() && ! mbPopulationCo.getSuperiorCode().equals("")){
            wrapper.likeRight("superiorCode",  mbPopulationCo.getSuperiorCode());
        }
        if(null != mbPopulationCo.getZhen() && ! mbPopulationCo.getZhen().equals("")){
            wrapper.likeRight("superiorCode",  mbPopulationCo.getZhen());
        }
        if(null != mbPopulationCo.getChun() && ! mbPopulationCo.getChun().equals("")){
            wrapper.eq("superiorCode",  mbPopulationCo.getChun());
        }
        if(mbPopulationCo.getHosnumarray()!=null && !mbPopulationCo.getHosnumarray().equals("")){
            wrapper.in("superiorCode",mbPopulationCo.getHosnumarray().split(","));
        }
        wrapper.eq("isAvailable",  "1");
        wrapper.orderByAsc("houseNumber");
        return mbPopulationMapper.selectPage(page,wrapper);
    }


    /**
     * @describe 根据id 查询 村民
     * @param mbPopulation
     * @Return com.menhai.personmanagement.entity.MbPopulation
     * @Date 2021/12/14 11:51
     * @author shikun
     */
    public MbPopulation selectByid(MbPopulation mbPopulation){
        return mbPopulationMapper.selectById(mbPopulation);
    }


    /**
     * @describe 年龄分类
     * @param
     * @Return java.util.List<com.menhai.personmanagement.entity.vo.FrontPageVo>
     * @Date 2021/12/20 10:44
     * @author shikun
     */
    public List<FrontPageVo> ageclassification(String superiorCode){
        return mbPopulationMapper.ageclassification(superiorCode);
    };

    /**
     * @describe 健康比例
     * @param superiorCode
     * @Return java.util.List<com.menhai.personmanagement.entity.vo.FrontPageVo>
     * @Date 2022/1/21 14:02
     * @author shikun
     */
    public List<FrontPageVo> healthyratio(String superiorCode){
        return mbPopulationMapper.healthyratio(superiorCode);
    };

    /**
     * @describe 性别分类
     * @param
     * @Return java.util.List<com.menhai.personmanagement.entity.vo.FrontPageVo>
     * @Date 2021/12/20 11:38
     * @author shikun
     */
    public List<FrontPageVo> genderclassification(String superiorCode){
        return mbPopulationMapper.genderclassification(superiorCode);
    };

    /**
     * @describe 来源分类
     * @param
     * @Return java.util.List<com.menhai.personmanagement.entity.vo.FrontPageVo>
     * @Date 2021/12/20 11:59
     * @author shikun
     */
    public List<FrontPageVo> sourceclassification(String superiorCode){
        return mbPopulationMapper.sourceclassification(superiorCode);
    };

    /**
     * @describe 首页 数字
     * @param
     * @Return com.menhai.personmanagement.entity.vo.FrontPageVo
     * @Date 2021/12/20 10:40
     * @author shikun
     */
    public FrontPageVo frontpagenumber(String superiorCode){
        //户籍数
        int householdregistration = mbPopulationMapper.selectByfamilyNumberOrderCount(superiorCode);
        //总人数
        QueryWrapper<MbPopulation> filterquery = new QueryWrapper<>();
        filterquery.likeRight("superiorCode",superiorCode);
       String totalpeople = String.valueOf(mbPopulationMapper.selectCount(filterquery));
       //男
        QueryWrapper<MbPopulation> male = new QueryWrapper<>();
        male.eq("sex","男");
        male.likeRight("superiorCode",superiorCode);
        String malenumber  = String.valueOf(mbPopulationMapper.selectCount(male));
        //女
        QueryWrapper<MbPopulation> female = new QueryWrapper<>();
        female.eq("sex","女");
        female.likeRight("superiorCode",superiorCode);
        String femalenumber  = String.valueOf(mbPopulationMapper.selectCount(female));
        //汉族
        QueryWrapper<MbPopulation> han = new QueryWrapper<>();
        han.eq("nation","汉族");
        han.likeRight("superiorCode",superiorCode);
        String hannumber  = String.valueOf(mbPopulationMapper.selectCount(han));
        //傣族
        QueryWrapper<MbPopulation> dai = new QueryWrapper<>();
        dai.eq("nation","傣族");
        dai.likeRight("superiorCode",superiorCode);
        String dainumber  = String.valueOf(mbPopulationMapper.selectCount(dai));

        FrontPageVo frontPageVo = new FrontPageVo();
        frontPageVo.setHouseholdregistration(String.valueOf(householdregistration));
        frontPageVo.setTotalpeople(totalpeople);
        frontPageVo.setMale(malenumber);
        frontPageVo.setFemale(femalenumber);
        frontPageVo.setHannumber(hannumber);
        frontPageVo.setDainumber(dainumber);
        return frontPageVo;
    }


    public List<MbPopulation> findPopulation(String name,String sex,String age1,String age2,String idnumber,String phone,String state,String local,String levelnum,String zhen,String cun,String hosnumstr,String[] hosnumArray){
        QueryWrapper queryWrapper = new QueryWrapper();
        if(notnull(name)){
            queryWrapper.like("name",name);
        }
        if(notnull(sex)){
            queryWrapper.eq("sex",sex);
        }
        if(notnull(age1)){
            queryWrapper.ge("age",age1);
        }
        if(notnull(age2)){
            queryWrapper.le("age",age2);
        }
        if(notnull(idnumber)){
            queryWrapper.eq("idnumber",idnumber);
        }
        if(notnull(phone)){
            queryWrapper.eq("telephony",phone);
        }
        if(notnull(state)){
            queryWrapper.eq("state",state);
        }
        if(notnull(local)){
            queryWrapper.eq("local",local);
        }
        if(notnull(cun)){
            queryWrapper.eq("superiorCode",cun);
        }else if(notnull(zhen)){
            queryWrapper.likeRight("superiorCode",zhen);
        }else {
            if (notnull(levelnum)) {
                queryWrapper.likeRight("superiorCode", levelnum);
            }
        }
        if(notnull(hosnumstr)&&!"null".equals(hosnumstr)){
        	queryWrapper.in("superiorCode", hosnumArray);
        }
        return mbPopulationMapper.selectList(queryWrapper);
    }

    public boolean notnull(String val){
        if(null != val && !val.equals("") && !val.equals("undefined")){
            return true;
        }
        return false;
    }

    public boolean batchInser(List<MbPopulationTemplete> list, int id){
        SysUser sysUser = sysUserMapper.selectById(id);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        String time = df.format(new Date());// new Date()为获取当前系统时间
//        String superiorName = "";
//        String temp[] = sysUser.getType().split(",");
//
//        List<Codelist> codelists = codelistMapper.getCodeValueByCodeName(temp);
//        for (Codelist c : codelists){
//            superiorName += c.getCodeValue()+",";
//        }
//        superiorName = superiorName.substring(0, superiorName.length()-1);


//        String code = "";
//        switch(codelists.size()){
//            case 1:
//                superiorName = codelists.get(0).getCodeValue();
//                code = superiorName;
//                break;
//            case 2:
//                superiorName = codelists.get(0).getCodeValue()+","+codelists.get(1).getCodeValue();
//                code = codelists.get(1).getCodeValue();
//                break;
//            case 3:
//                superiorName = codelists.get(0).getCodeValue()+","+codelists.get(1).getCodeValue()+","+codelists.get(2).getCodeValue();
//                code = codelists.get(2).getCodeValue();
//                break;
//            default:
//                superiorName = sysUser.getHosnum();
//                code = sysUser.getHosnum();
//                break;
//        }
        try{
            List<Codelist> xianlist =  codelistService.getHospital();
            List<Codelist> zhenlist =  codelistService.getZhenHospital();
            List<Codelist> chunlist =  codelistService.getChunHospital();

//
//            String finalSuperiorName = superiorName;
//            String finalSuperiorCode = code;
            list.forEach(mbPopulationTemplete -> {
                MbPopulation mbPopulation = new MbPopulation();
                mbPopulation.setName(mbPopulationTemplete.getName());
                mbPopulation.setAge(mbPopulationTemplete.getAge());
                mbPopulation.setSex(mbPopulationTemplete.getSex());
                mbPopulation.setBirthday(mbPopulationTemplete.getBirthday());
                mbPopulation.setCredentials(mbPopulationTemplete.getCredentials());
                mbPopulation.setIdnumber(mbPopulationTemplete.getIdnumber());
                mbPopulation.setMarriage(mbPopulationTemplete.getMarriage());
                mbPopulation.setTelephony(mbPopulationTemplete.getTelephony());
                mbPopulation.setNewaddress(mbPopulationTemplete.getNewaddress());
                mbPopulation.setAddress(mbPopulationTemplete.getAddress());
                mbPopulation.setUrgentname(mbPopulationTemplete.getUrgentname());
                mbPopulation.setUrgentphone(mbPopulationTemplete.getUrgentphone());
                mbPopulation.setLocal(mbPopulationTemplete.getLocal());
                mbPopulation.setChronic(mbPopulationTemplete.getChronic());
                mbPopulation.setState(mbPopulationTemplete.getState());
                mbPopulation.setFamilycode(mbPopulationTemplete.getFamilycode());
                mbPopulation.setHouseholder(mbPopulationTemplete.getHouseholder());
                mbPopulation.setNation(mbPopulationTemplete.getNation());
                mbPopulation.setNationality(mbPopulationTemplete.getNationality());
                mbPopulation.setBloodtype(mbPopulationTemplete.getBloodtype());
                mbPopulation.setEducation(mbPopulationTemplete.getEducation());
                mbPopulation.setHouseNumber(mbPopulationTemplete.getHouseNumber());
                mbPopulation.setHeight(mbPopulationTemplete.getHeight());
                mbPopulation.setWeight(mbPopulationTemplete.getWeight());
                mbPopulation.setIsAvailable(1);
                mbPopulation.setCreatedate(time);

//                mbPopulation.setSuperiorCode(finalSuperiorCode);
//                mbPopulation.setSuperiorName(finalSuperiorName);
                String scode = "";
                String name = "";
                if(mbPopulationTemplete.getSuperiorNameOne() != "" && null != mbPopulationTemplete.getSuperiorNameOne()){
                    List<Codelist> value = xianlist.stream().filter(v -> v.getCodeName().equals(mbPopulationTemplete.getSuperiorNameOne())).collect(Collectors.toList());
                    name = value.get(0).getCodeValue();
                    scode = value.get(0).getCodeValue();
                }
                if(mbPopulationTemplete.getSuperiorNameTwo() != "" && null != mbPopulationTemplete.getSuperiorNameTwo()){
                    List<Codelist> value = zhenlist.stream().filter(v -> v.getCodeName().equals(mbPopulationTemplete.getSuperiorNameTwo())).collect(Collectors.toList());
                    name += ","+ value.get(0).getCodeValue();
                    scode = value.get(0).getCodeValue();
                }
                if(mbPopulationTemplete.getSuperiorNameThree() != "" && null != mbPopulationTemplete.getSuperiorNameThree()){
                    List<Codelist> value = chunlist.stream().filter(v -> v.getCodeName().equals(mbPopulationTemplete.getSuperiorNameThree())).collect(Collectors.toList());
                    name += ","+ value.get(0).getCodeValue();
                    scode = value.get(0).getCodeValue();
                }
                mbPopulation.setSuperiorCode(scode);
                mbPopulation.setSuperiorName(name);
                mbPopulationMapper.insert(mbPopulation);
            });
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    public MbPopulation searchByIdnumber(String idnumber){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("idnumber", idnumber);
        return mbPopulationMapper.selectOne(queryWrapper);
    }

    public Map findByNameAndPhone(String id, String name, String phone,String level){
        Map map = new HashMap();
        QueryWrapper qw = new QueryWrapper();
        if(!StringUtils.isEmpty(id)){
            qw.eq("id", id);
        }
        if(!StringUtils.isEmpty(name)){
            qw.eq("name",name);
        }
        if(!StringUtils.isEmpty(phone)){
            qw.eq("telephony", phone);
        }
        if(!StringUtils.isEmpty(level)){
            qw.likeRight("superiorCode",level);
        }
        List<MbPopulation> list = mbPopulationMapper.selectList(qw);
        if(list.size() < 1){
            return null;
        }
        map.put("renkou", list);


        QueryWrapper jzqw = new QueryWrapper();
        jzqw.eq("population", list.get(0).getId());
        jzqw.last("limit 5");
        map.put("zhenliao", treatmentInformationMapper.selectList(jzqw));


        map.put("tijian",healthCheckMapper.getDataByPopulationId(list.get(0).getId()));

        map.put("zhongyi", reportHealthrecordMapper.getReportByPopulationId(list.get(0).getId()));
        return map;
    }

    public int saveArchives(SaveArchivesVo saveArchivesVo){
        try {
            mbPopulationMapper.updateById(saveArchivesVo.getRenkou());
            if(null != saveArchivesVo.getTijian()) {
                healthCheckMapper.update(saveArchivesVo.getTijian());
            }
            if(null != saveArchivesVo.getZhongyi()) {
                reportHealthrecordMapper.update(saveArchivesVo.getZhongyi());
            }
            return 1;
        }catch (Exception e){
            e.printStackTrace();
            return -1;
        }
    }

    /**
     * 更新检测时间
     * @param checkTime
     * @param id
     * @param idnumber
     * @return
     */
    public int updateCheckTime(String checkTime,String id,String idnumber){
        return mbPopulationMapper.updateCheckTime(checkTime,id,idnumber);
    }
}
